/* Copyright (c) 2009, 2010, 2011 Damian Kmiecik <d0zoenator@gmail.com>
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   * Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in
     the documentation and/or other materials provided with the
     distribution.
   * Neither the name of the copyright holders nor the names of
     contributors may be used to endorse or promote products derived
     from this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE. */

#include <stdlib.h>
#include <avr/interrupt.h>
#include <avr/io.h>
#include <util/delay.h>
#include <avr/wdt.h>
#include <stdio.h>
#include "config.h"
#include "main.h"
#include "timer.h"
#include "stdout.h"
#include "enc28j60.h"
#include "ethernet.h"

#ifndef	ARP_DEBUG
	#define ARP_DEBUG(...)
#endif

uint8_t ethBuffer[MTU_SIZE+1];
struct ETH_ETHERNET_HEADER *ethernet = (struct ETH_ETHERNET_HEADER*)&ethBuffer[ETHERNET_OFFSET];
struct ETHERNET eth;
struct timer_item_s eth_timer;
#ifdef DEBUG_ARPTCP
	struct timer_item_s eth_debug_timer;
#endif

uint32_t htons32(const uint32_t val)
{
	return HTONS32(val);
}

uint16_t htons(const uint16_t val)
{
	return HTONS(val);
}

void ETHpacketProcess(void)
{
	// Check packet type
	if (ethernet->type == HTONS(ETH_TYPE_ARP))
	{
		ARPreply();
	} else {
		// If IP
		if (ethernet->type == HTONS(ETH_TYPE_IP))
		{
			// If MyIP
			if ((ip->destIp == settings.ip) || (ip->destIp == 0xFFFFFFFF))
			{
				ARPentryAdd();
				// If ICMP
				if (ip->protocol == IP_PROTOCOL_ICMP)
				{
					switch (icmp->type)
					{
					case ICMP_REQUEST:
						ICMPsend(ip->sourceIp, ICMP_REPLY, icmp->seqNum,
								icmp->id);
						break;
#if ETHERNET_SENDING_PING
					case ICMP_REPLY:
						ARP_DEBUG("ETH PONG\n", NULL);
						if (eth.ping_ip == ip->sourceIp)
						{
							ARP_DEBUG("ETH PONG IP\n", NULL);
							eth.ping = 1;
						}
						break;
#endif
					}
					return;
				} else {
					if (ip->protocol == IP_PROTOCOL_TCP)
					{
						TCPpacketProcess();
					}
					if (ip->protocol == IP_PROTOCOL_UDP)
					{
						UDPpacketProcess();
					}
				}
			} else {
				// If broadcast
				if (ip->destIp == (uint32_t)0xFFFFFFFF)
				{
					if (ip->protocol == IP_PROTOCOL_UDP)
					{
						UDPpacketProcess();
					}
				}
			}
		}
	}
}

void ETHgetData(void)
{
	// If data present
	if (NETCARD_INT)
	{
		uint16_t length = enc28j60ReceivePacket(MTU_SIZE, ethBuffer);
		if (length > 0)
			ETHpacketProcess();
	}
	// Check timers
	if (timerExpiredReset(&eth_timer))
	{
		TCPtimerDo();
		ARPtimerDo();
	}
#ifdef DEBUG_ARPTCP
	if (timerExpiredReset(&eth_debug_timer))
	{
		#ifdef DEBUG_TCP
		TCPprintTable();
		#endif
		#ifdef DEBUG_ARP
		ARPprintTable();
		#endif
	}
#endif
}

void ETHmakeHeader(ip_t destIp)
{
	uint8_t a;
	// Check routing
	if ((destIp & settings.mask) != (settings.ip & settings.mask))
	{
		// use router
		destIp = settings.gate;
	}
	// Search for MAC in ARP table
	a = ARPentrySearch(destIp);
	if (a != MAX_ARP_ENTRY)
	{
		for (uint8_t i = 0; i < 6; i++)
		{
			ethernet->destMac[i] = arpTable[a].arp_t_mac[i];
			ethernet->sourceMac[i] = settings.mac[i];
		}
		return;
	}
	for (uint8_t i = 0; i < 6; i++)
	{
		ethernet->destMac[i] = 0xFF;
		ethernet->sourceMac[i] = settings.mac[i];
	}
}

void ethernetInit(void)
{
	// Start timers
	timerSet_s(&eth_timer, 1);
	#ifdef DEBUG_ARPTCP
		timerSet_s(&eth_debug_timer, 20);
	#endif
	ethernetArp();
	while (1)
	{
		uint8_t a = ARPentrySearch(settings.gate);
		if (a != MAX_ARP_ENTRY)
		{
			arpTable[a].arp_t_time = ARP_TIME_OFF;
			break;
		} else
			ARPrequest(settings.gate);
		_delay_ms(500);
		wdt_reset();
		// If data present
		if (NETCARD_INT)
		{
			uint16_t length = enc28j60ReceivePacket(MTU_SIZE, ethBuffer);
			if (length > 0)
				if (ethernet->type == HTONS(ETH_TYPE_ARP))
					ARPreply();
		}
	}
}

void ethernetArp(void)
{
	// Get static ARP of NetGate
//	uint8_t a = ARPentrySearch(settings.gate);
//	if (a != MAX_ARP_ENTRY)
//		arpTable[a].arp_t_time = ARP_TIME_OFF;
//	else
//		ARPrequest(settings.gate);
#ifdef USE_NTP
	// Get NTP ARP#endif
	uint8_t a = ARPentrySearch(settings.ntp);
	if (a != MAX_ARP_ENTRY)
		arpTable[a].arp_t_time = ARP_TIME_OFF;
	else
		ARPrequest(settings.ntp);
#endif
#ifdef USE_DNS
	// Get NTP ARP#endif
	a = ARPentrySearch(settings.dns);
	if (a != MAX_ARP_ENTRY)
		arpTable[a].arp_t_time = ARP_TIME_OFF;
	else
		ARPrequest(settings.dns);
#endif
}
